﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using System.Configuration;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using System.Runtime.InteropServices;
using com.zjgis.arcengineutility;
using System.Data.Common;
using pnmodel;
using com.zjgis.control;

namespace WindowsApplication1.dialog
{
    public partial class QueryResultForm : Form
    {
        private QueryResultForm()
        {
            InitializeComponent();
        }
        static QueryResultForm form = null;
        public static QueryResultForm Instance
        {
            get
            {
                if(form == null || form.IsDisposed){
                    form = new QueryResultForm();
                }
                return form;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "")
            {
                MessageBox.Show("输入关键字为空");
                return;
            }
        }

        private void QueryResultForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        public IMapControl2 MapControl
        {
            set
            {
                map = value;
            }
        }

        public void Clear()
        {
            treeView1.Nodes.Clear();
        }

        public void ShowQueryResult(string sql,IMapControl2 c2)
        {
            DbConnection conn = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            DbCommand command = conn.CreateCommand();
            command.CommandText = sql;
            DbDataReader reader = command.ExecuteReader();
            string tablename = ConfigurationManager.AppSettings["建筑图层"];
            string idname = ConfigurationManager.AppSettings["用电建筑编号"];
            string fieldname = idname;
            QueryResultForm form = QueryResultForm.Instance;
            form.Clear();
            TreeNode root = form.treeView1.Nodes.Add("用电建筑信息");
            int tagindex = reader.GetOrdinal(idname);
            int shapeindex = reader.GetOrdinal("shape");
            int shapetypeindex = reader.GetOrdinal("shapetype");
            while (reader.Read())
            {
                int shapetype = int.Parse(reader.GetValue(shapetypeindex).ToString());
                IGeometry geom1 = PnGeometryUtility.GetGeometry(shapetype + 2000, reader.GetString(shapeindex));
                string tag = reader.GetString(tagindex);
                TreeNode tnode = root.Nodes.Add(tag);
                int fcount = reader.FieldCount;
                for (int i = 0; i < fcount - 1; i++)
                {
                    if (i == tagindex || i == shapeindex || i == shapetypeindex)
                    {
                        continue;
                    }
                    string aliasname = reader.GetName(i);
                    string value = reader.GetValue(i).ToString();
                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                    TreeNode node = tnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + value);
                    ContextMenuStrip cms = new ContextMenuStrip();
                    node.ContextMenuStrip = cms;
                    ToolStripItem strip = cms.Items.Add("编辑");
                    strip.Click += delegate
                    {
                        InputBox box = InputBox.Show("编辑属性 " + aliasname, node.Text.Substring(node.Text.LastIndexOf(':') + 1).TrimStart(' '));
                        if (box.DialogResult == DialogResult.OK)
                        {
                            string text = box.GetInputText();
                            DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                            conn1.Open();
                            DbCommand comm1 = conn1.CreateCommand();
                            try
                            {
                                comm1.CommandText = "update 用电建筑信息 set " + aliasname + " = :p1 where 建筑统一编码 = '" + tag + "'";
                                DbParameter ter = comm1.CreateParameter();
                                ter.Value = text;
                                ter.ParameterName = "p1";
                                comm1.Parameters.Add(ter);
                                if (comm1.ExecuteNonQuery() > 0)
                                {
                                    node.Text = aliasname.PadRight(20 - length, ' ') + " : " + text.ToString();
                                    MessageBox.Show("更新成功");
                                }
                                else
                                {
                                    MessageBox.Show("更新失败!");
                                }
                            }
                            catch (Exception ex) { MessageBox.Show("更新失败,原因：" + ex.Message); }
                            finally
                            {
                                conn1.Close();
                            }
                        }
                    };
                }
                ContextMenuStrip cm = new ContextMenuStrip();
                Form1.addContextMenuStrip(geom1, ref cm, c2);
                ToolStripItem item = cm.Items.Add("删除");
                item.Click += delegate
                {
                    DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                    conn1.Open();
                    string sql1 = "delete from 用电建筑信息 where 建筑统一编码 = '" + tag + "'";
                    DbCommand command1 = conn1.CreateCommand();
                    command1.CommandText = sql1;
                    if (command1.ExecuteNonQuery() != 0)
                    {
                        tnode.Remove();
                    }

                    sql1 = "update 建筑 set hasdata = 0 where buildingid = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    sql1 = "update 建筑 set 建筑统一编码 = '' where 建筑统一编码 = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    sql1 = "delete from 用电建筑 where 建筑统一编码 = '" + tag + "'";
                    command1.CommandText = sql1;
                    command1.ExecuteNonQuery();
                    c2.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground,null,geom1.Envelope);
                    conn1.Close();
                };
                tnode.ContextMenuStrip = cm;
            }
            reader.Close();
            conn.Close();
        }

        public void AddLayerAndQueryFilter(IQueryFilter qfilter, IFeatureLayer flayer, string titleField)
        {
            IActiveView av = map.ActiveView;
            TreeView treeView = treeView1;
            string layername = flayer.Name;
            IFeatureCursor fcursor = flayer.Search(qfilter, true);
            DbConnection conn = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            DbCommand command = conn.CreateCommand();
            try
            {
                IFeature feature = fcursor.NextFeature();
                if (feature != null)
                {
                    TreeNode root = treeView.Nodes.Add(layername);
                    int labelIndex = feature.Fields.FindField(titleField);
                    IFeatureClass fclass = flayer.FeatureClass;
                    while (feature != null)
                    {
                        string label = feature.get_Value(labelIndex).ToString();
                        TreeNode labelnode = root.Nodes.Add(label);
                        ContextMenuStrip cm = new ContextMenuStrip();
                        ToolStripItem moveItem = cm.Items.Add("移动至");
                        ToolStripItem zoomItem = cm.Items.Add("缩放至");
                        ToolStripItem flashItem = cm.Items.Add("闪烁");

                        cm.Tag = feature.ShapeCopy;

                        moveItem.Click += delegate(object sender, EventArgs e)
                        {
                            IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                            double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                            double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                            IPoint op = new PointClass();
                            op.X = x1;
                            op.Y = y1;
                            IEnvelope env1 = av.Extent;
                            env1.CenterAt(op);
                            av.Extent = env1;
                            av.Refresh();
                        };

                        zoomItem.Click += delegate(object sender, EventArgs e)
                        {
                            IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                            IEnvelope env2 = geom1.Envelope;
                            if (env2.Dimension == esriGeometryDimension.esriGeometry0Dimension)
                            {
                                double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                                double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                                IPoint op = new PointClass();
                                op.X = x1;
                                op.Y = y1;
                                IEnvelope env1 = av.Extent;
                                env1.CenterAt(op);
                                av.Extent = env1;
                            }
                            else
                            {
                                av.Extent = env2;
                            }
                            av.Refresh();
                        };
                        flashItem.Click += delegate(object sender, EventArgs e)
                        {
                            IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                            FlashUtility.FlashGeometry(geom1, map);
                        };
                        labelnode.ContextMenuStrip = cm;
                        for (int findex = 0; findex < feature.Fields.FieldCount; findex++)
                        {
                            if (fclass.ShapeFieldName == feature.Fields.get_Field(findex).Name)
                            {
                                continue;
                            }
                            string aliasname = feature.Fields.get_Field(findex).AliasName;
                            int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                            labelnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + feature.get_Value(findex).ToString());
                        }
                        if (layername == ConfigurationManager.AppSettings["建筑图层"])
                        {
                            command.CommandText = "select * from 用电建筑信息  where 建筑统一编码 = '" + label + "'";
                            IDataReader reader = command.ExecuteReader();
                            if(reader.Read())
                            {
                                for (int z = 0; z < reader.FieldCount; z++)
                                {
                                    string aliasname = reader.GetName(z);
                                    int length = UnicodeEncoding.Default.GetByteCount(aliasname) - aliasname.Length;
                                    labelnode.Nodes.Add(aliasname.PadRight(20 - length, ' ') + " : " + reader.GetValue(z).ToString());
                                }
                            }
                            reader.Close();
                        }
                        feature = fcursor.NextFeature();
                    }
                    root.Expand();
                }
                Marshal.ReleaseComObject(fcursor);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            conn.Close();
        }

        public void AddLayerAndQueryFilter(IQueryFilter qfilter, IGeoFeatureLayer flayer, string titleField)
        {
            IActiveView av = map.ActiveView;
            TreeView treeView = treeView1;
            string layername = flayer.Name;
            IFeatureCursor fcursor = flayer.DisplayFeatureClass.Search(qfilter, true);
            IFeature feature = fcursor.NextFeature();
            if (feature != null)
            {
                TreeNode root = treeView.Nodes.Add(layername);
                int labelIndex = feature.Fields.FindField(titleField);
                IFeatureClass fclass = flayer.FeatureClass;
                while (feature != null)
                {
                    string label = feature.get_Value(labelIndex).ToString();
                    TreeNode labelnode = root.Nodes.Add(label);
                    ContextMenuStrip cm = new ContextMenuStrip();
                    ToolStripItem moveItem = cm.Items.Add("移动至");
                    ToolStripItem zoomItem = cm.Items.Add("缩放至");
                    ToolStripItem flashItem = cm.Items.Add("闪烁");

                    cm.Tag = feature.ShapeCopy;

                    moveItem.Click += delegate(object sender, EventArgs e)
                    {
                        IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                        double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                        double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                        IPoint op = new PointClass();
                        op.X = x1;
                        op.Y = y1;
                        IEnvelope env1 = av.Extent;
                        env1.CenterAt(op);
                        av.Extent = env1;
                        av.Refresh();
                    };

                    zoomItem.Click += delegate(object sender, EventArgs e)
                    {
                        IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                        IEnvelope env2 = geom1.Envelope;
                        if (env2.Dimension == esriGeometryDimension.esriGeometry0Dimension)
                        {
                            double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                            double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                            IPoint op = new PointClass();
                            op.X = x1;
                            op.Y = y1;
                            IEnvelope env1 = av.Extent;
                            env1.CenterAt(op);
                            av.Extent = env1;
                        }
                        else
                        {
                            av.Extent = env2;
                        }
                        av.Refresh();
                    };
                    flashItem.Click += delegate(object sender, EventArgs e)
                    {
                        IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                        FlashUtility.FlashGeometry(geom1, map);
                    };
                    labelnode.ContextMenuStrip = cm;
                    for (int findex = 0; findex < feature.Fields.FieldCount; findex++)
                    {
                        if (fclass.ShapeFieldName == feature.Fields.get_Field(findex).Name)
                        {
                            continue;
                        }
                        labelnode.Nodes.Add(feature.Fields.get_Field(findex).AliasName.PadRight(20, ' ') + " : " + feature.get_Value(findex).ToString());
                    }
                    feature = fcursor.NextFeature();
                }
                root.Expand();
            }
            Marshal.ReleaseComObject(fcursor);
        }
        IMapControl2 map;

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            if (node.Nodes.Count == 0 && node.ContextMenuStrip != null)
            {
                System.Drawing.Point p = e.Location;
                p.Offset(this.Location);
                node.ContextMenuStrip.Show(p);
            }
        }
    }
}
